package com.chatbot.service;

import com.chatbot.dto.*;
import com.chatbot.entity.Character;
import com.chatbot.entity.CharacterConversation;
import com.chatbot.entity.CharacterMessage;
import com.chatbot.entity.User;
import com.chatbot.repository.CharacterRepository;
import com.chatbot.repository.CharacterConversationRepository;
import com.chatbot.repository.CharacterMessageRepository;
import com.chatbot.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CharacterService {
    
    @Autowired
    private CharacterRepository characterRepository;
    
    @Autowired
    private CharacterConversationRepository conversationRepository;
    
    @Autowired
    private CharacterMessageRepository messageRepository;

    @Autowired
    private UserRepository userRepository;

    @Value("${dashscope.api.key}")
    private String apiKey;

    // 创建新角色
    @Transactional
    public CharacterDTO createCharacter(Long userId, CreateCharacterRequest request) {
        // 检查角色名是否已存在
        if (characterRepository.existsByUser_IdAndName(userId, request.getName())) {
            throw new RuntimeException("角色名称已存在");
        }

        User user = userRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));

        Character character = new Character();
        character.setUser(user);
        character.setName(request.getName());
        character.setAge(request.getAge());
        character.setPersonality(request.getPersonality());
        character.setOccupation(request.getOccupation());
        character.setBackground(request.getBackground());
        character.setRelationships(request.getRelationships());
        character.setAdditionalInfo(request.getAdditionalInfo());
        character.setSceneSettings(request.getSceneSettings());
        character.setLanguageStyle(request.getLanguageStyle());
<<<<<<< HEAD
        character.setVoiceId(request.getVoiceId() != null ? request.getVoiceId() : "zhitian_emo");
        character.setVoiceSettings(request.getVoiceSettings());
=======
>>>>>>> 6790c0f5bc6f08cedb0c7499f37461b422457426

        Character savedCharacter = characterRepository.save(character);
        return convertToDTO(savedCharacter);
    }

    // 获取用户的所有角色
    public List<CharacterDTO> getUserCharacters(Long userId) {
        List<Character> characters = characterRepository.findByUser_Id(userId);
        return characters.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    // 获取角色详情
    public CharacterDTO getCharacter(Long userId, Long characterId) {
        Character character = characterRepository.findByUser_IdAndCharacterId(userId, characterId);
        if (character == null) {
            throw new RuntimeException("角色不存在");
        }
        return convertToDTO(character);
    }

    // 更新角色信息
    @Transactional
    public CharacterDTO updateCharacter(Long userId, Long characterId, CreateCharacterRequest request) {
        Character character = characterRepository.findByUser_IdAndCharacterId(userId, characterId);
        if (character == null) {
            throw new RuntimeException("角色不存在");
        }

        // 如果更改了名称，检查新名称是否已存在
        if (!character.getName().equals(request.getName()) && 
            characterRepository.existsByUser_IdAndName(userId, request.getName())) {
            throw new RuntimeException("角色名称已存在");
        }

        character.setName(request.getName());
        character.setAge(request.getAge());
        character.setPersonality(request.getPersonality());
        character.setOccupation(request.getOccupation());
        character.setBackground(request.getBackground());
        character.setRelationships(request.getRelationships());
        character.setAdditionalInfo(request.getAdditionalInfo());
        character.setSceneSettings(request.getSceneSettings());
        character.setLanguageStyle(request.getLanguageStyle());
<<<<<<< HEAD
        character.setVoiceId(request.getVoiceId() != null ? request.getVoiceId() : "zhitian_emo");
        character.setVoiceSettings(request.getVoiceSettings());
=======
>>>>>>> 6790c0f5bc6f08cedb0c7499f37461b422457426

        Character updatedCharacter = characterRepository.save(character);
        return convertToDTO(updatedCharacter);
    }

    // 删除角色
    @Transactional
    public void deleteCharacter(Long userId, Long characterId) {
        Character character = characterRepository.findByUser_IdAndCharacterId(userId, characterId);
        if (character == null) {
            throw new RuntimeException("角色不存在");
        }
        
        // 删除角色相关的所有对话和消息
        List<CharacterConversation> conversations = conversationRepository.findByUser_IdAndCharacter_CharacterId(userId, characterId);
        for (CharacterConversation conversation : conversations) {
            messageRepository.deleteByCharacterConversation_CharacterConversationId(conversation.getCharacterConversationId());
        }
        conversationRepository.deleteAll(conversations);
        
        characterRepository.delete(character);
    }

    // 将实体转换为DTO
    private CharacterDTO convertToDTO(Character character) {
        CharacterDTO dto = new CharacterDTO();
        dto.setCharacterId(character.getCharacterId());
        dto.setUserId(character.getUser().getId());
        dto.setName(character.getName());
        dto.setAge(character.getAge());
        dto.setPersonality(character.getPersonality());
        dto.setOccupation(character.getOccupation());
        dto.setBackground(character.getBackground());
        dto.setRelationships(character.getRelationships());
        dto.setAdditionalInfo(character.getAdditionalInfo());
        dto.setSceneSettings(character.getSceneSettings());
        dto.setLanguageStyle(character.getLanguageStyle());
        dto.setCreatedAt(character.getCreatedAt());
        dto.setUpdatedAt(character.getUpdatedAt());
        return dto;
    }
} 